package com.qf.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 54110 on 2021/3/2.
 */
public class JwtUtils {


    public String securtToken(Map map){
        //声明私钥
        Algorithm shop = Algorithm.HMAC256("shop");
        //声明头部
        Map headMap = new HashMap<>();
        headMap.put("alg","HS256");
        headMap.put("typ","jwt");
        //创建token
        //1.声明头部
        String token = JWT.create().withHeader(headMap)
                .withSubject("shop jwt")
                .withIssuer("qianfeng")
                .withIssuedAt(new Date())
                //声明载荷部分
                .withClaim("userName", map.get("userName").toString())
                .withClaim("id", map.get("id").toString())
                //签名
                .sign(shop);

        return token;
    }

    public Map Verifier(String token){
        //声明私钥
        Algorithm algorithm = Algorithm.HMAC256("shop");
        //声明解密对象
        JWTVerifier jwtVerifier = JWT.require(algorithm).withIssuer("qianfeng").build();
        //声明解密对象进行解密
        DecodedJWT verify = jwtVerifier.verify(token);
        //获取我们的自定义载荷内容
        Claim id = verify.getClaim("id");
        Claim userName = verify.getClaim("userName");
        Map map = new HashMap<>();
        map.put("id",id.asString());
        map.put("userName",userName.asString());
        return map;

    }

}
